package cn.edu.bs.service.impl;

import cn.edu.bs.config.AppConfig;
import cn.edu.bs.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.UUID;

@Service("fileService")
public class FileServiceImpl implements FileService {

    private final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    private static final String UPLOAD_PATH = AppConfig.UPLOAD_PATH;

    private Boolean flag = true;

    private String path;

    public FileServiceImpl() {
        URL url = FileServiceImpl.class.getClassLoader().getResource("");
        assert url != null;
        File uploadDir = new File(url.getPath() + UPLOAD_PATH);
        if (!uploadDir.exists() || !uploadDir.isDirectory()) {
            flag = uploadDir.mkdirs();
        }
        if (flag) {
            path = uploadDir.getPath();
        }
        logger.info("文件上传目录: {}", path);
    }

    @Override
    public File save(File file) throws FileNotFoundException {
        String filePath = file.getPath();
        String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
        return save(new FileInputStream(filePath), fileName);
    }

    @Override
    public File save(InputStream inputStream, String fileName) throws FileNotFoundException {
        if (!flag) {
            throw new FileNotFoundException("文件上传目录无效，请联系管理员。上传目录地址：" + this.path);
        }
        fileName = genFileName(fileName);
        File file = new File(fileName);
        try {
            OutputStream out = new FileOutputStream(file);
            byte[] buffer = new byte[2048];
            int count = 0;
            while ((count = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, count);
                out.flush();
            }
            inputStream.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (file.exists()) {
            return file;
        } else {
            return null;
        }
    }

    @Override
    public File save(MultipartFile multipartFile) throws IOException {
        return this.save(multipartFile.getInputStream(), multipartFile.getName());
    }

    @Override
    public String genFileName(String fileName) {
        GregorianCalendar calendar = new GregorianCalendar();
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH) + 1;
        Integer day = calendar.get(Calendar.DAY_OF_MONTH);
        String suffix = fileName.lastIndexOf('.') != -1 ? fileName.substring(fileName.indexOf('.')) : "";
        String newFileName = UUID.randomUUID().toString();
        // like /~path~/2017/11/11/
        String currentFileDirPath = path + File.separator + year + File.separator + month + File.separator + day + File.separator;
        File currentFileDir = new File(currentFileDirPath);
        if (!currentFileDir.exists()) {
            boolean flag = currentFileDir.mkdirs();
        }
        return currentFileDirPath + newFileName + suffix;
    }

}
